<template>
  <uv-transition :show="value">
    <view class="upgrade-popup">
      <view class="main">
        <uv-avatar :src="appIcon" shape="square" size="200rpx" class="app-icon" />
        <view class="version">发现新版本{{ info.versionName }}</view>
        <view class="content">
          <text class="title">更新内容：</text>
          <view class="desc" v-html="info.content || '无'"></view>
        </view>
        <view class="content">
          <text class="title">更新时间：</text>
          <text class="desc">{{ info.versionUpdateDate }}</text>
        </view>
        <view class="content" v-if="isStartDownload">
          <text class="title">其它下载：</text>
          <text class="desc link" @click="handleBrowser">跳转浏览器下载</text>
        </view>
        <!--下载状态-进度条显示 -->
        <view class="footer" v-if="isStartDownload">
          <view
            class="progress-view"
            :class="{ active: !hasProgress }"
            @click="handleInstallApp"
          >
            <!-- 进度条 -->
            <view v-if="hasProgress" style="height: 100%">
              <view class="txt">{{ percentText }}</view>
              <view class="progress" :style="setProStyle"></view>
            </view>
            <view v-else>
              <view class="btn upgrade force">{{
                isDownloadFinish ? "立即安装" : "下载准备..."
              }}</view>
            </view>
          </view>
        </view>
        <!-- 强制更新 -->
        <view class="footer" v-if="info.forceUpdate == 1">
          <view class="btn upgrade force" v-if="!isStartDownload" @click="handleUpgrade">
            立即更新
          </view>
        </view>
        <!-- 可选择更新 -->
        <view class="footer" v-else>
          <view class="btn close" @click="handleClose">以后再说</view>
          <view class="btn upgrade" v-if="!isStartDownload" @click="handleUpgrade">
            立即更新
          </view>
        </view>
      </view>
    </view>
  </uv-transition>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { webSrc } from "@/common/mothed.js";
import appIcon from "@/static/login/login.png"; // 图标
import { downloadApp, installApp } from "./upgrade.js";

const props = defineProps({
  value: {
    type: Boolean,
    default: false,
  },
  info: {
    type: Object,
    default: () => {},
  },
});
const emit = defineEmits(["update:value"]);

const isDownloadFinish = ref(false); //是否下载完成
const hasProgress = ref(false); //是否能显示进度条
const currentPercent = ref(0); //当前下载百分比
const isStartDownload = ref(false); //是否开始下载
const fileName = ref(""); //下载后app本地路径名称

//设置进度条样式，实时更新进度位置
const setProStyle = computed(() => {
  return {
    width: (510 * currentPercent.value) / 100 + "rpx",
  };
});

//百分比文字
const percentText = computed(() => {
  let percent = currentPercent.value;
  if (typeof percent !== "number" || isNaN(percent)) return "下载准备...";
  if (percent < 100) return `下载中${percent}%`;
  return "立即安装";
});

watch(props, () => {
  if (props.value) {
    // #ifdef APP-PLUS
    // 禁止下拉刷新
    const pages = getCurrentPages();
    const page = pages[pages.length - 1];
    const currentWebview = page.$getAppWebview();
    currentWebview.setStyle({
      pullToRefresh: {
        support: !props.value,
        style: plus.os.name === "Android" ? "circle" : "default",
      },
    });
    // #endif
  }
});

// 更新
const handleUpgrade = () => {
  // #ifdef APP-PLUS
  if (props.info.downloadUrl) {
    isStartDownload.value = true;
    //开始下载App
    downloadApp(webSrc(props.info.downloadUrl), (current) => {
      //下载进度监听
      hasProgress.value = true;
      currentPercent.value = current;
    })
      .then((name) => {
        //下载完成
        isDownloadFinish.value = true;
        fileName.value = name;
        if (fileName.value) {
          //自动安装App
          handleInstallApp();
        }
      })
      .catch((e) => {
        uni.showToast({
          title: JSON.stringify(e),
          icon: "none",
          duration: 5000,
        });
        console.log(e, "e");
      });
  } else {
    uni.showToast({
      title: "下载链接不存在",
      icon: "none",
    });
  }
  // #endif
  // #ifdef H5
  uni.showToast({
    title: "H5仅作效果预览，不可下载",
    icon: "none",
  });
  handleClose();
  // #endif
};
//安装app
const handleInstallApp = () => {
  //下载完成才能安装，防止下载过程中点击
  if (isDownloadFinish.value && fileName.value) {
    installApp(fileName.value, () => {
      //安装成功,关闭升级弹窗
      handleClose();
    });
  }
};
// 浏览器下载
const handleBrowser = () => {
  // #ifdef APP-PLUS
  plus.runtime.openURL(webSrc(props.info.downloadUrl));
  // #endif
  // #ifdef H5
  window.location.href = webSrc(props.info.downloadUrl);
  // #endif
};
//关闭
const handleClose = () => {
  hasProgress.value = false;
  isStartDownload.value = false;
  isDownloadFinish.value = false;
  // #ifdef APP-PLUS
  plus.downloader.clear();
  // #endif
  emit("update:value", false);
};
</script>
<style lang="scss" scoped>
.upgrade-popup {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 980;
  background-color: rgba(0, 0, 0, 0.5);
}

.main {
  position: absolute;
  top: 50%;
  left: 50%;
  padding: 30rpx;
  max-width: 610rpx;
  transform: translate(-50%, -50%);
  box-sizing: border-box;
  background-color: #fff;
  border-radius: 20rpx;
  .app-icon {
    position: absolute;
    right: 10rpx;
    top: -110rpx;
  }
  .version {
    font-size: 32rpx;
    color: #4ea770;
    font-weight: 700;
    width: 100%;
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    letter-spacing: 1px;
  }

  .content {
    margin-top: 40rpx;
    .title {
      font-size: 28rpx;
      font-weight: 700;
      color: #000000;
    }
    .desc {
      box-sizing: border-box;
      margin-top: 20rpx;
      font-size: 28rpx;
      color: #6a6a6a;
      max-height: 40vh;
      overflow-y: auto;
    }
    .link {
      color: #409eff;
      text-decoration: underline;
      &:active {
        color: #1a4659;
      }
    }
  }

  .footer {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    flex-shrink: 0;
    margin-top: 60rpx;

    .btn {
      width: 246rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      z-index: 999;
      height: 80rpx;
      box-sizing: border-box;
      font-size: 32rpx;
      border-radius: 10rpx;
      letter-spacing: 2rpx;

      &.force {
        width: 500rpx;
      }

      &.close {
        border: 1px solid #e0e0e0;
        margin-right: 25rpx;
        color: #000;
      }

      &.upgrade {
        background-color: #4ea770;
        color: #fff;
      }
    }

    .progress-view {
      width: 510rpx;
      height: 80rpx;
      display: flex;
      position: relative;
      align-items: center;
      border-radius: 6rpx;
      background-color: #dcdcdc;
      display: flex;
      justify-content: flex-start;
      padding: 0px;
      box-sizing: border-box;
      border: none;
      overflow: hidden;

      &.active {
        background-color: #4ea770;
      }

      .progress {
        height: 100%;
        background-color: #4ea770;
        padding: 0px;
        box-sizing: border-box;
        border: none;
        transition: width 0.3s;
        border-top-left-radius: 10rpx;
        border-bottom-left-radius: 10rpx;
      }

      .txt {
        font-size: 26rpx;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        color: #fff;
      }
    }
  }
}
</style>
